﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace SimpleFile
{
    public class FileFilter
    {
        public FileFilter(string directory, bool isWeb, params string[] extensions)
        {
            if (string.IsNullOrWhiteSpace(directory))
                throw new Exception("目录为空");
            if (isWeb)
            {
                if (!directory.StartsWith("~"))
                    throw new Exception("不是服务器路径");
            }
            else
            {
                if (!Directory.Exists(directory))
                    throw new Exception("该路径不存在");
            }
            _acceptExtension = new List<string>();
            ServerDirectory = directory;
            if (extensions.Length == 0)
                throw new Exception("后缀为空");
            foreach (var ex in extensions)
            {
                if (!ex.StartsWith("."))
                    _acceptExtension.Add("." + ex);
                else
                    _acceptExtension.Add(ex);
            }
        }

        public bool Accept(string fileExtension)
        {
            if(string.IsNullOrWhiteSpace(fileExtension))
                throw new Exception("文件后缀名为空");
            fileExtension=fileExtension.Trim();
            if (!fileExtension.StartsWith("."))
                fileExtension = "." + fileExtension;
            return _acceptExtension.Exists(x => x == fileExtension);
        }

        public string ServerDirectory { get; private set; }
        private List<string> _acceptExtension;
    }

}
